/// <reference path="../../../../node_modules/@types/crypto-js/index.d.ts" />
import {AfterViewInit, Component, OnDestroy, OnInit, ViewChild} from '@angular/core';
import * as CryptoJS from 'crypto-js';
import {Router} from '@angular/router';
import {UserService} from '../../services/api/user.service';
import {AlertComponent, MessageService, ServerConfigService} from '../../../ng-tools';
import {Subscription, timer} from 'rxjs';
import {ThemeService} from '../../services/theme.service';
import {PlatformLocation} from '@angular/common';
import {configFilePath} from '../../app.module';
import {TicketService} from '../../services/api/ticket.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
})
export class LoginComponent implements OnInit, AfterViewInit, OnDestroy {

  sub: Subscription = new Subscription();
  errorMessage: string;
  showMessage = false;
  alterOption = {
    theme: 'danger',
    data: '',
    position: 'center'
  };
  @ViewChild('alert') private alert: AlertComponent;
  constructor(private ticketService: TicketService,
              private router: Router,
              public theme: ThemeService,
              private serverConfig: ServerConfigService,
              private location: PlatformLocation,
              private message: MessageService) {
  }

  ngOnInit() {
  }

  login(loginForm) {
      // this.router.navigate(['main/oplatform']).catch(reason => {
      //     console.log(reason);
      // });
    if (loginForm.valid) {
      const data = Object.assign({}, loginForm.value);
      this.ticketService.login(data).subscribe((resp) => {
        console.log(resp);
        if (resp.body.success) {
          localStorage.setItem('token',  resp.body.returnValue.token);
          this.router.navigate(['main/oplatform']).catch(reason => {});
        } else {
          this.alterOption.theme = 'danger';
          this.alterOption.data = resp.body.msg;
          this.alert.show(this.alterOption, 2000);
        }
      });
      // this.ticketService.post(this.ticketService.urls.login, data, {headers: {'auth': 'false'}, observe: 'response'}).subscribe(resp => {
      //
      // });
    }
  }

  enter(e, loginForm) {
    if (e.keyCode === 13) {
      this.login(loginForm);
    }
  }

  showErrorMessage(msg: string, time: number = 2000) {
    this.showMessage = true;
    this.errorMessage = msg;
    if (time !== 0) {
      this.hideErrorMessage(time);
    }
  }

  hideErrorMessage(time: number = 0) {
    timer(time).subscribe(() => {
      this.showMessage = false;
      this.errorMessage = null;
    });
  }

  ngAfterViewInit(): void {
    const i = this.message.getMessage('sign out to login', this).subscribe((next) => {
      if (next.data) {
        const msg = `您的账户已在 ${next.data.ip.toString()} 登录`;
        this.showErrorMessage(msg, 0);
      }
    });
    this.sub.add(i);
  }

  ngOnDestroy(): void {
    this.sub.unsubscribe();
  }

}
